{% extends "sitebase.html" %}
{% block title %}{{ BUILDING_NAME }} Energy Portal{% endblock %}

{% block extra_scriptsCSS_imports %}
<link href="/site-media/anytime/anytimec.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="/site-media/flot/jquery.flot.js"></script>
<script type="text/javascript" src="/site-media/flot/jquery.flot.stack.min.js"></script>
<script type="text/javascript" src="/site-media/flot/jquery.flot.navigate.min.js"></script>
<script type="text/javascript" src="/site-media/flot/jquery.flot.selection.min.js"></script>
<script type="text/javascript" src="/site-media/flot/jquery.flot.axislabels.js"></script>
<script type="text/javascript" src="/site-media/flot/jquery.flot.resize.min.js"></script>
<script type="text/javascript" src="/site-media/anytime/anytimec.js"></script>
<script type="text/javascript" src="/site-media/bootstrap/bootstrap-modal.js"></script>
<link rel="stylesheet" href="/site-media/jgauge/css/jgauge.css" type="text/css" /> <!-- CSS for jGauge styling. -->
<!--[if IE]><script type="text/javascript" language="javascript" src="js/excanvas.min.js"></script><![endif]--> <!-- Extends canvas support to IE. (Possibly buggy, need to look into this.) -->
<script type="text/javascript" src="/site-media/jgauge/js/jQueryRotate.min.js"></script> <!-- jQueryRotate plugin used for needle movement. -->
<script type="text/javascript" src="/site-media/jgauge/js/jgauge-0.3.0.a3.js"></script> <!-- jGauge JavaScript. -->
<script type="text/javascript" src="/site-media/psMathStats/psMathStats.min.js"></script>
<script type="text/javascript" src="/site-media/jquery-sparkline/jquery.sparkline.js"></script>


<!-- customs -->
<script type="text/javascript" src="/site-media/campenportJS/buildingpage/gaugeSetup.js"></script>
<script type="text/javascript" src="/site-media/campenportJS/smap/query.js"></script>
<script type="text/javascript" src="/site-media/campenportJS/buildingpage/statsCalc.js"></script>
{% endblock %}

{% block extra_css_inline %}
	.hero-unit {
		padding-top: 20px;
		padding-bottom: 20px;
		padding-right: 20px;
		padding-left: 20px;
	}
	footer {
		 margin-top: 0px; 
	}
{% endblock %}

{% block header_title %}
<a href="/buildings/{{ SHORT_NAME }}" style="color:#000000;">{{ BUILDING_NAME }} Energy Portal</a>
{% endblock %}
{% block header_subtitle %}
Drag on the graph to zoom in.
{% endblock %}

{% block content_inside %}
<div class="hero-unit" style="margin-top:-10px;text-align:center;" ><div style="margin:0px auto; width:80%">
    <ul class="pills">
    <li class="active"><a href="#">Jump Down:</a></li>
    <li><a href="#" onclick="scrollDownTo('graphMain')">Graph &#9660;</a></li>
	<li><a href="#" onclick="scrollDownTo('statstab')">Baseline Statistics &#9660;</a></li>
    <li><a href="#" onclick="scrollDownTo('enviro')">Environment &#9660;</a></li>
    <li><a href="#" onclick="scrollDownTo('relatives')">Relative &#9660;</a></li>
    <li><a href="#" onclick="scrollDownTo('props')">Properties &#9660;</a></li>
    </ul></div>
</div>
<div class="hero-unit" style="min-height:610px;margin-top:-80px;" id="graphMain">
<h2>Live Power Consumption Graph (Default 1 Day): </h2> Start Time: <input class="span4" type = "text" id="date2" size=36>&nbsp; &nbsp;  End Time: <input class="span4" type="text" id="date" size=36> &nbsp; &nbsp; <input type = "button" class="btn primary" value = "Load/Refresh Data" id="refresh"> &nbsp; &nbsp;<input type="checkbox" id="autoup" name="autoup" value="10" checked /> Autoupdate (15 min)
<br><br>
<div id="graph" >
<!-- contains graph generated by flot -->
<div id="placeholder" style = "position:absolute;width:900px;height:520px;">
    
</div><div id="loading" style="position:absolute;width:300px;top:450px;left:50%;margin-left:-150px;text-align:center;padding:7px 0 0 0;font:bold 12px Arial, Helvetica, sans-serif;">  
    <div id="loading_inside">Loading data, please wait..  </div>
    <img src="/site-media/images/ajax-loader.gif" alt="loading.." />  <div id="timewrap" style="font:bold 10px Arial, Helvetica, sans-serif;">Your query should take about <span id="appxtime">3.63</span> seconds. <br> Stuck? Try <a href="javascript:location.reload(true);">refreshing</a>.</div>
    </div> 
</div>
</div>
<div class="hero-unit" style="margin-top:-15px;min-height:40px;" id="statstab"><div style="float:left;"><h2>Baseline Statistics:   </h2></div><div style="float:right;"><ul class="pills">
    <li class="active"><a href="#" onclick="scrollToTop()">Jump Up &#9650;</a></li></ul></div><br>
	
	
</div>

<div class="hero-unit" style="margin-top:-50px;min-height:40px;" >
	<div style="background-color:#FFFFFF;">	
	<table class="bordered-table zebra-striped" id="sortedbuildings">
        <thead>
          <tr>
            <th><h3>Statistic (Calculated over above Time Period)</h3></th>

            <th><h3>Value</h3></th>
          </tr>
        </thead>
        <tbody>
			<tr>
				<td><p>Root Mean Squared Deviation</p></td>
				<td><h3><span class="stats1">Baseline Not Available</span></h3></td>
			</tr>
			<tr>
				<td><p>Root Mean Squared Deviation (Percent of Mean)</p></td>
				<td><h3><span class="stats2">Baseline Not Available or Range too Large</span></h3></td>
			</tr>
		</tbody>
      </table>
	</div>
</div>

<!--UNCOMMENT TO KEEP WORKING ON TRANSPARENT GRAPH<div class="hero-unit" id="dialogGoesHere" style="min-height:300px;">testing flot resize</div> -->



<div class="hero-unit" style="margin-top:-15px;min-height:40px;" id="enviro"><div style="float:left;"><h2>Environment:   </h2></div><div style="float:right;"><ul class="pills">
    <li class="active"><a href="#" onclick="scrollToTop()">Jump Up &#9650;</a></li></ul></div>
</div>
<div class="row" style="margin-top:-50px;">
	<div class="span-one-third">
		<div class="hero-unit" style="text-align:center;">

<p>Outside <strong>Air Temperature</strong>: <br> <span class="tempBox"></span>&nbsp; &nbsp; / &nbsp; &nbsp; 
Past 24 Hours: <br><span class="dynamicsparkline" style="background-color:rgba(0, 0, 0, 0.1);">Loading..</span></p>
		</div>
	</div>

<div class="span-one-third">
		<div class="hero-unit" style="text-align:center;">

<p>Outside <strong>Humidity</strong>: <br> <span class="humBox"></span>&nbsp; &nbsp; / &nbsp; &nbsp; 
Past 24 Hours: <br><span class="dynamicsparklineHum" style="background-color:rgba(0, 0, 0, 0.1);">Loading..</span></p>
		</div>
	</div>
<div class="span-one-third">
		<div class="hero-unit" style="text-align:center;margin-top:-17px;">

<p>Outside <strong>Air Pressure</strong>: <br><span class="pressBox"></span>&nbsp; / &nbsp; 
Past 24 Hours: <br><span class="dynamicsparklinePress" style="background-color:rgba(0, 0, 0, 0.1);">Loading..</span></p>
		</div>
	</div>

</div>


<div class="hero-unit" style="margin-top: -15px;min-height:40px;" id="relatives"><div style="float:left;"><h2>Relative Statistics:</h2></div><div style="float:right;"><ul class="pills">
    <li class="active"><a href="#" onclick="scrollToTop()">Jump Up &#9650;</a></li></ul></div></div>
<div class="row" style="margin-top: -50px;">

<div class="span-one-third">
	<div class="hero-unit" style="min-height:200px;text-align:center;"> <h3><a href="#" rel="popover" title="How is this calculated?" data-placement="above" data-content="Deviation from Baseline is calculated by taking the actual kW usage, subtracting the baseline, and finally dividing this result by the baseline. It is effectively a calculation of error; thus a negative percentage means that the building is using less power than usual, while a positive percentage implies exactly the opposite." style="color:#000000;">Current Baseline Deviation</a></h3><div style="width:180px;margin:0 auto;"><div id="kWvsBaseline" class="jgauge" style="width:180px;margin:0 auto;"></div></div></div>
</div>

<div class="span-one-third">
	<div class="hero-unit" style="min-height:200px;text-align:center;"> <h3><a href="#" rel="popover" title="How is this calculated?" data-placement="above" data-content="% of Total Campus (kW) is calculated by taking a building's current power usage and dividing it by the sum of the power usage of all campus buildings for which data is available. It is designed to be compared to the gauge to the right, % of Total Campus (SqFt)." style="color:#000000;">% of Total Campus (kW)</a></h3><div style="width:180px;margin:0 auto;"><div id="gaugeTwo" class="jgauge" style="width:180px;margin:0 auto;"></div></div></div>
</div>
<div class="span-one-third">
	<div class="hero-unit" style="min-height:200px;text-align:center;margin-top:-17px;"> <h3><a href="#" rel="popover" title="How is this calculated?" data-placement="above" data-content="% of Total Campus (SqFt) is calculated by taking a building's square footage and dividing it by the sum of the square footage of all campus buildings for which data is available. It is designed to be compared to the gauge to the left, % of Total Campus (kW)." style="color:#000000;">% of Total Campus (SqFt)</a></h3><div style="width:180px;margin:0 auto;"><div id="gaugeThree" class="jgauge" style="width:180px;margin:0 auto;"></div></div></div>
</div>


</div> <!-- endrow -->



<div class="row" id="props">
<div class="span8" style="text-align:center;">
<ul class="media-grid">

        <li>
          <a href="{{ PIC_SRC }}"  data-controls-modal="modal-from-dom2" data-backdrop="true" data-keyboard="true">
            <img class="thumbnail" src="{{ PIC }}" alt="">
          </a>
        </li>
              </ul>
</div>
<div class="span8">
<h2>About {{ BUILDING_NAME }}:</h2> <p>{{ INFO }} </p><br> <br>
<div style="text-align:right;"><button data-controls-modal="modal-from-dom" data-backdrop="true" data-keyboard="true" class="btn large primary">More Info >></button></div>


</div>
</div>

<div class="row">
	<div class="span8">
		<h2>Building Stats:</h2> 
		<h4>
			<ul>
			<li>Square Footage: {{ STATS_SQFT }} </li>
			<li>Year Built: {{ STATS_YEAR }} </li>
			<li>Available Data Sources: <span id="UUIDcount"></span> </li>
			</ul>
		</h4>
	</div>
	<div class="span8">
		<h2>Location:</h2>
		<div class="mapboxdisp" style="padding-top:10px;overflow:hidden;height:{{ desired_height }}px;width:{{ desired_width }}px;">
			<div style="margin-left:-{{ x_min }}px;margin-top:-{{ y_min }}px;">
				<img src="/site-media/campusmap.png" width="1232" height="1067" style="border:0;" alt="campusmap" usemap="#map" id="image" />
							<map id="map" name="map">
							<!-- coordinates stored in the db were obtained using the following: -->
								<!-- #$-:Image map file created by GIMP Image Map plug-in -->
								<!-- #$-:GIMP Image Map plug-in by Maurits Rijk -->
								<!-- #$-:Please do not edit lines starting with "#$" -->
								<!-- #$VERSION:2.3 -->
								<!-- #$AUTHOR:sagark  -->
							<!-- end cooordinates were obtained -->
							<!-- generates imagemap from coordinates stored in database -->
							{% for building in buildings|dictsort:"longname" %}
<area shape="poly" coords="{{ building.map_coords }}" href="/buildings/{{ building.shortname }}/" alt="{{ building.shortname }}"   />{% endfor %}
							</map>
			</div>
		</div>
	</div>
</div>
<div class="hero-unit" style="height:40px;padding:0px;margin-top:15px;margin-bottom:0px;text-align:center;" >
	<div style="margin:0px auto; width:80%">
    <ul class="pills">
    <li class="active"><a href="#">Jump Up:</a></li>
    <li><a href="#" onclick="scrollDownTo('graphMain')">Graph &#9650;</a></li>
	<li><a href="#" onclick="scrollDownTo('statstab')">Baseline Statistics &#9650;</a></li>
    <li><a href="#" onclick="scrollDownTo('enviro')">Environment &#9650;</a></li>
    <li><a href="#" onclick="scrollDownTo('relatives')">Relative &#9650;</a></li>
    <li><a href="#" onclick="scrollDownTo('props')">Properties &#9650;</a></li>
	<li><a href="#" onclick="scrollToTop()">Top &#9650;</a></li>
    </ul></div>
</div>
<div id="modal-from-dom" class="modal hide fade">
	<div class="modal-header">
    	<a href="#" class="close">&times;</a>
        	<h3>You are being directed to an external link.</h3>
    </div>
    <div class="modal-body">
		<p>Although we hope the link to be useful, sites change. Thus, we cannot necessarily endorse the link to which you are being directed: {{ STATS_ALTINFO }}</p>
    </div>
    <div class="modal-footer">
    	<a href="{{ STATS_ALTINFO }}" target="_blank" onClick="$('#modal-from-dom').modal('hide')" class="btn primary">Continue to External Site</a>
        <a onClick="$('#modal-from-dom').modal('hide')" class="btn secondary">Go Back</a>
	</div>
</div>
<div id="modal-from-dom2" class="modal hide fade">
	<div class="modal-header">
    	<a href="#" class="close">&times;</a>
        	<h3>You are being directed to an external link.</h3>
    </div>
    <div class="modal-body">
		<p>Here's a link to the building picture source. Although we obtained the image from this link, sites change. Thus, we cannot necessarily endorse the link to which you are being directed: {{ PIC_SRC }}</p>
    </div>
    <div class="modal-footer">
    	<a href="{{ PIC_SRC }}" target="_blank" onClick="$('#modal-from-dom').modal('hide')" class="btn primary">Continue to External Site</a>
        <a onClick="$('#modal-from-dom2').modal('hide')" class="btn secondary">Go Back</a>
	</div>
</div>
<!--
<div id="pastdialog1" title="Basic dialog"><div id="wrap" style="position:absolute;width:75%;height:80%;">
<div id="flotholder2" style="position:absolute;width:127%;height:120%;overflow:hidden;"></div></div> 
</div>
-->
{% endblock %}
{% block extend_contact_url %}{{ A_SHORT_NAME }}{% endblock %}
{% block random_extras %}
<script type="text/javascript">
/*
 * the following two functions are helpers for smooth anchor-scrolling
 */
function scrollDownTo(itemID){
     	$('html,body').animate({scrollTop: $("#"+itemID).offset().top-40},'slow');
}
function scrollToTop(){
     	$('html,body').animate({scrollTop: 0},'slow');
}


/*
 * Handler function for Bootstrap Popovers
 */
$(function () {
              $("a[rel=popover]")
                .popover({
                  offset: 10
                })
                .click(function(e) {
                  e.preventDefault()
                })
            }
)


/*
function pastDialog1(callback){
	$( "#pastdialog1" ).dialog({dialogClass: 'transparent',});
	$('#pastdialog1').dialog({ dialogClass:'transparent',   width:350, height:300 , buttons: {"Background On/Off": function() { switchBG(); } }}).dialog('widget').position({ my: 'left top', at: 'left top', of: $("#dialogGoesHere") });
	callback();
}
*/
/*
function runGraph(){
	$.plot($("#flotholder2"), [[[1,1], [2, 2], [3, 3]]], {
			colors: ["blue", "black"],
        	legend: { noColumns: 2 },
        	xaxis: { tickDecimals: 0 },
        	selection: { mode: "x" },
			grid: {hoverable: true, clickable: true},
			xaxes: [{
				axisLabel: 'Time',
			}],
			yaxes: [{
				position: 'left',
				axisLabel: 'Power Consumption (kW)',
			}],
			series: {shadowSize: 0},
    	});
	$('.transparent').css('background-color','transparent');
	$('.transparent').css('overflow', 'hidden');
}

function switchBG(){
	//switches background of transparent dialog
	if($('.transparent').css('background-color')=='rgba(0, 0, 0, 0)'){
		$('.transparent').css('background-color','white');
	}
	else{
		$('.transparent').css('background-color','transparent');
	}
}
*/


$(document).ready(function() {
	//time setup
	window.datefmt = "%W %M %e, %Y %H:%i"; //the format used by AnyTime, shared everywhere
	window.converter = new AnyTime.Converter( { format: window.datefmt }); //create a converter
	//create two time periods to set defaults
	nowDate = new Date();
	startDate = new Date(); 
	startDate.setTime(nowDate - 86400000);
	//Set values of user time-fields
	$("#date").val(converter.format(nowDate)); 
	$("#date2").val(converter.format(startDate));
	//Create pickers for each time-field
	AnyTime.picker( "date", { format: datefmt, firstDOW: 0 } );
	AnyTime.picker( "date2", { format: datefmt, firstDOW: 0 } );
	//end time setup



	var endtime = window.converter.parse($("#date").val()).getTime();
	var starttime = window.converter.parse($("#date2").val()).getTime();

	appxtime = (((endtime-starttime)/(86400000))*0.1069416301 + 3.52531359);
	appxtime = Math.floor(appxtime*100)/100.00;
	
	appxwindow = document.getElementById('appxtime');
	appxwindow.innerHTML = appxtime;


	//Initialize gauges
	kWvsBaselineG.init();
	gaugeTwo.init();
	gaugeThree.init();
	//Set defaults
	kWvsBaselineG.setValue(000);
	gaugeTwo.setValue(000);
	gaugeThree.setValue(000);


	//Start Fetching Data, displaying things
	environmentData(); //Gets environment data, independent of other data gets

	//setup global variable replacements for passing along kW Timeseries data
	window.mainFlotTimeseries = {} //A dictionary for the data for the flot chart
	window.retrievedStatistics = {} //A dictionary to hold computed/retrieved data

/* Old code for transparent floating graphs
        pastDialog1(runGraph);
        $( "#pastdialog1" ).dialog();
	$('#pastdialog1').dialog({ width: 350, height: 300 }).dialog('widget').position({ my: 'left top', at: 'left top', of: $("#dialogGoesHere") });
*/

	getKWflotData();
	setInterval("autoUpdater()", 900000);
});

$("#refresh").click(function() {
	var endtime = window.converter.parse($("#date").val()).getTime();
	var starttime = window.converter.parse($("#date2").val()).getTime();

	loadingwindow = document.getElementById('loading_inside');
	loadingwindow.innerHTML = "Loading Data, Please Wait...";
	appxtime = (((endtime-starttime)/(86400000))*0.1069416301 + 3.52531359);
	appxtime = Math.floor(appxtime*100)/100.00;
	
	appxwindow = document.getElementById('appxtime');
	appxwindow.innerHTML = appxtime;
	$("#timewrap").show();



	$("#placeholder").empty();
	$("#loading").show();
	getKWflotData();
});



/* 
 * Fetches environmentData for past 24 hours, regardless of user's time input
 * This is due to a restriction on the part of sparklines
 * Runs independently of other queries.
 */
function environmentData(){
	//var converter = new AnyTime.Converter( { format: datefmt });
	var endtime = window.converter.parse($("#date").val()).getTime();
	var starttime = endtime - 86400000;
	loadingwindow = document.getElementById('loading_inside');
	loadingwindow.innerHTML = "Fetching Outside Environment Data";

	httpGetData(function(resp){
		//callback
		var passtoSpark = resp[0]['Readings'];
		var passfinal = [];
		for (x=0; x<passtoSpark.length; x++){
			passfinal.push(Math.round(((passtoSpark[x][1]*9/5+32)*1000))/1000);
		}
		$('.dynamicsparkline').sparkline(passfinal);
		$('.tempBox').html("<strong>" + passfinal[passfinal.length-1] + "&ordm;F" + "</strong>");
		}, 0, "8abdca01-0454-5a59-b4d0-ca46dead8c58", starttime, endtime, 0, 0);


	httpGetData(function(resp){
	//callback
		var passtoSparkHum = resp[0]['Readings'];
		var passfinalHum = [];
		for (x=0; x<passtoSparkHum.length; x++){
			passfinalHum.push(passtoSparkHum[x][1]);
		}
		$('.dynamicsparklineHum').sparkline(passfinalHum);
		$('.humBox').html("<strong>" + passfinalHum[passfinalHum.length-1] + "% (rh)</strong>");
		}, 0, "5e9c2fa4-3650-500d-a51f-a7a34f9089fe", starttime, endtime, 0, 0);


	httpGetData(function(resp){
	//callback
		var passtoSparkPress = resp[0]['Readings'];
		var passfinalPress = [];
		for (x=0; x<passtoSparkPress.length; x++){
			passfinalPress.push(passtoSparkPress[x][1]);
		}
		$('.dynamicsparklinePress').sparkline(passfinalPress);
		$('.pressBox').html("<strong>" + passfinalPress[passfinalPress.length-1] + " mbar</strong>");
		}, 0, "17f7cd48-5b30-5dc4-90d1-5b5e7c57b792", starttime, endtime, 0, 0);

}


/*
 * 15 minute AutoUpdater
 * Refreshes (User-Time) based data 
 * 15 min interval is based on 15 min interval of sMAP apply nansum
 */
function autoUpdater(){
	loadingwindow = document.getElementById('loading_inside');
	loadingwindow.innerHTML = "Autoupdating, Please Wait";

	if ($('input[name=autoup]').is(':checked')){
	var nowDate = new Date();
	$("#date").val(window.converter.format(nowDate));
	getKWflotData();
	environmentData();
	}
}


/*
 * Starts chain to fetch data for main flot chart
 */
function getKWflotData() {
	getBaselineTags(function(resp){
		loadingwindow = document.getElementById('loading_inside');
		loadingwindow.innerHTML = "Fetching Baseline Data";
		output = [];
		sendUUIDcount = document.getElementById('UUIDcount');
		sendUUIDcount.innerHTML = resp.length;
		if (resp.length==0){ //continues the fetch chain for buildings without a baseline
			noBaselineHandler();  //buildings getting data the new way launch into noBaselineHandler()
		}
		else{ //continues the fetch chain for buildings with a baseline
					output.push([resp[0]["uuid"],resp[0]["Metadata"]["Extra"]["Operator"]]); //REMOVE THIS
					window.mainFlotTimeseries[resp[0]["Metadata"]["Extra"]["Operator"]] = resp[0]["uuid"]; //for autoupdater use, at somepoint, rewrite the rest to make this replace output
			runHttpGetData(output);
		}
	}, "{{ QUERY_ID }}");
}



function noBaselineHandler(){
	var endtime = window.converter.parse($("#date").val()).getTime();
	var starttime = window.converter.parse($("#date2").val()).getTime();
	loadingwindow = document.getElementById('loading_inside');
	loadingwindow.innerHTML = "No Baseline Found, Fetching Real Data";
	if((endtime-starttime)<86400010){
		// less than or equal to a day + error
		fieldsize = 'minute';
		inc = '15';
	} else {
		// less than or equal to 3 weeks + error
		fieldsize = 'hour';
		inc = '1';
	} 
	getBuildingNansum(function(resp){
		passalong = [resp, [{"uuid": "BLANK", "Readings": []}]];
		window.mainFlotTimeseries['actualkW'] = resp[0]['Readings']
		var needToavg = [];
	

		if (endtime-starttime<=1209600000){
			for (x in passalong[0][0]['Readings']){
				needToavg.push(passalong[0][0]['Readings'][x][1]);
			}
			var psArray = new ps.array(needToavg);
			var avg = psArray.mean();
			var avgArr = [[starttime, avg], [endtime, avg]];
		}
		else {
				var avgArr = 0; 
		}

		types = ["subsampled sum", "baseline-01"];
		drawGraph(avgArr);
		setAllTheGauges(resp[0]['Readings'][resp[0]['Readings'].length-1], resp[0]['Readings'][resp[0]['Readings'].length-1]);
		runStats(window.mainFlotTimeseries['actualkW'], window.mainFlotTimeseries['baselineData'], avgArr);

	}, "{{ NEW_QUERY_ID }}", starttime, endtime, fieldsize, inc);
}




function baselineHandler(latest, numMod, typeOrder){
	var converter = new AnyTime.Converter( { format: datefmt });
	var endtime = converter.parse($("#date").val()).getTime();
	var starttime = converter.parse($("#date2").val()).getTime();
	loadingwindow = document.getElementById('loading_inside');
	loadingwindow.innerHTML = "Baseline Found, Fetching Real Data";
	if((endtime-starttime)<86400010){
		// less than or equal to a day + error
		// use 15 minute intervals
		fieldsize = 'minute';
		inc = '15';
	} else {
		// less than or equal to 3 weeks + error
		fieldsize = 'hour';
		inc = '1';
	}

	httpGetTagsStreamHandler(function(resp, inp, inptype, numMod){
		//console.log(resp);
		inp[numMod] = resp;
		//console.log(inp);
		if (endtime-starttime<=1209600000){
			for (x in inp[numMod][0]['Readings']){
				needToavg.push(inp[numMod][0]['Readings'][x][1]);
			}
			var psArray = new ps.array(needToavg);
			var avg = psArray.mean();
			var avgArr = [[starttime, avg], [endtime, avg]];
			}
			else {var avgArr = 0; }

		window.mainFlotTimeseries['actualkW'] = resp[0]['Readings'];
		drawGraph(avgArr);
		setAllTheGauges(inp[numMod][0]['Readings'][inp[numMod][0]['Readings'].length-1], inp[Math.abs(1-numMod)][0]['Readings'][inp[Math.abs(1-numMod)][0]['Readings'].length-1]);
		runStats(window.mainFlotTimeseries['actualkW'], window.mainFlotTimeseries['baselineData'], avgArr);

}, "apply nansum(axis=1) < paste < window(first, field='" + fieldsize + "', width=" + inc + ") < units to  data in (" + starttime + ", " + endtime + ") streamlimit 10000 where (Metadata/Extra/System = 'total' or Metadata/Extra/System = 'electric') and ((Properties/UnitofMeasure = 'kW' or Properties/UnitofMeasure = 'Watts') or Properties/UnitofMeasure = 'W') and Metadata/Location/Building like '{{ NEW_QUERY_ID }}%' and not Metadata/Extra/Operator like 'sum%' and not Path like '%demand' and not Path like '/Cory_Hall/Electric_5A7/ABC/real_power' and not Path like '/Cory_Hall/Electric_5B7/ABC/real_power'", latest, typeOrder, numMod);
}


function runHttpGetData(output) {
	latest = [];
	typeOrder = [];
	needToavg = [];
	var converter = new AnyTime.Converter( { format: datefmt });
	var endtime = converter.parse($("#date").val()).getTime();
	var starttime = converter.parse($("#date2").val()).getTime();
	

	for(x=0; x<output.length; x++){
	httpGetData(function(resp, typeInput){
		typeOrder.push(typeInput);
		latest.push(eval(resp));
		window.mainFlotTimeseries['baselineData'] = eval(resp)[0]['Readings'];
		if (output.length==latest.length){
			if (endtime-starttime<=1209600000){
			for (x in latest[0][0]['Readings']){
				needToavg.push(latest[0][0]['Readings'][x][1]);
			}
			var psArray = new ps.array(needToavg);
			var avg = psArray.mean();
			var avgArr = [[starttime, avg], [endtime, avg]];
			}
			else {var avgArr = 0; }
///FIX it up code here
			if(typeOrder[0]=="subsampled sum" && latest[0][0]['Readings'].length == 0 ){
				baselineHandler(latest, 0, typeOrder);
				return;
			}
			else if((typeOrder[0] == "baseline-01" && typeOrder.length==1) || (typeOrder[1]=="subsampled sum" && latest[1][0]['Readings'].length == 0)){
				
				if(typeOrder.length==1){
					typeOrder[1] = "subsampled sum";
				}
				baselineHandler(latest, 1, typeOrder);
				return;
			}



///END Fix it up code
			latest = drawGraph(avgArr);
			setAllTheGauges(latest[0][0]['Readings'][latest[0][0]['Readings'].length-1], latest[1][0]['Readings'][latest[1][0]['Readings'].length-1]);
			runStats(latest, typeOrder, avgArr);

		}
	}, latest, output[x][0], starttime, endtime, output, output[x][1]);
	}
}

function setAllTheGauges(lastActualkW, lastActualBaseline) {
	percent = Math.round((lastActualkW[1]-lastActualBaseline[1])/lastActualBaseline[1]*100);
	kWvsBaselineG.setValue(percent);
	callgetLatestWholeCampus(lastActualkW);
	gaugeThree.setValue({{ sqftPercent }});	
}

function callgetLatestWholeCampus(lastActualkW){
	getLatestWholeCampus(setMiddleGauge, lastActualkW);
}

function getLatestWholeCampus(callback, lastActualkW) {
	tempendtime = (new Date()).getTime();
    tempendtime -= 4200000;
	$.ajax({
		async: true,
		type: 'POST',
		url: '/ARDgetData/api/query?',
		data: "apply nansum(axis=1) < paste < window(first, field='minute', width=15) < units to  data in (" + (tempendtime-3000000) + " ," + tempendtime + ") streamlimit 10000 where (Metadata/Extra/System = 'total'  or Metadata/Extra/System = 'electric') and ((Properties/UnitofMeasure = 'kW' or Properties/UnitofMeasure = 'Watts') or Properties/UnitofMeasure = 'W') and not Metadata/Extra/Operator like 'sum%' and not Path like '%demand'",
		success: function(response) {
			callback(response, lastActualkW);
		}
	});
}

function setMiddleGauge(response, lastActualkW){
	wholecamp = response[0]['Readings'][response[0]['Readings'].length-1][1];
	thisbuildkW = lastActualkW[1];
	gaugeTwo.setValue(thisbuildkW/wholecamp*100);
}

/*
 * Draws the main (top-centered) flot chart on each page
 * Runs after all necessary data is collected
 */
function drawGraph(flatlineAvg){

	var buildupData = [];
	var labels = [];
	if(typeof mainFlotTimeseries['actualkW']=='object'){
		buildupData.push({label:"Actual Usage", "data":mainFlotTimeseries['actualkW']});
	}
	if(typeof mainFlotTimeseries['baselineData']=='object'){
		buildupData.push({label:"Predicted Usage", "data":mainFlotTimeseries['baselineData']});
	}

	//Now fix timezone offset for flot
	
	////Figure out what to do here!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
	needTzOffset = new Date();
	tzOffset = needTzOffset.getTimezoneOffset()*60000
	
	for (x=0; x<buildupData.length; x++){
		for (y=0; y<buildupData[x]["data"].length; y++){
			buildupData[x]["data"][y][0] -= tzOffset;
		}

		/*
		for (y=0; y<inputData[x][0]['Readings'].length; y++){
			inputData[x][0]['Readings'][y][0] = inputData[x][0]['Readings'][y][0]-tzOffset;
		} */
	}
 /*
	if (flatlineAvg != 0){
	flatlineAvg[0][0] -= tzOffset;
	flatlineAvg[1][0] -= tzOffset;
	}
	*/
	//end fix timezone offset for flot
	var options = {
			colors: ["blue", "black"],
        	legend: { noColumns: 2 },
        	xaxis: { tickDecimals: 0, mode:"time" },
        	selection: { mode: "x" },
			grid: {hoverable: true, clickable: true},
			xaxes: [{
				axisLabel: 'Time',
			}],
			yaxes: [{
				position: 'left',
				axisLabel: 'Power Consumption (kW)',
			}],
			series: {shadowSize: 0},
    	};

	var placeholder = $("#placeholder");

	placeholder.bind("plotselected", function (event, ranges) {
		$("#selection").text(ranges.xaxis.from.toFixed(1) + " to " + ranges.xaxis.to.toFixed(1));
		plot = $.plot(placeholder, buildupData, $.extend(true, {}, options, { xaxis: { min: ranges.xaxis.from, max: ranges.xaxis.to } }));
	});

	placeholder.bind("plotunselected", function (event) {
		$("#selection").text("");
	});

	var previousPoint = null;
    $("#placeholder").bind("plothover", function (event, pos, item) {
        $("#x").text(pos.x.toFixed(2));
        $("#y").text(pos.y.toFixed(2));

        if (true) {
            if (item) {
                if (previousPoint != item.dataIndex) {
                    previousPoint = item.dataIndex;
                    
                    $("#tooltip").remove();
                    var x = item.datapoint[0].toFixed(2),
                        y = item.datapoint[1].toFixed(2);
                    
					var tempdate = new Date(x/1+tzOffset);
                    showTooltip(item.pageX, item.pageY,
                                item.series.label + " on " + converter.format(tempdate)  + " was " + y + " kW");
                }
            }
            else {
                $("#tooltip").remove();
                previousPoint = null;            
            }
        }
    });

    $("#placeholder").bind("plotclick", function (event, pos, item) {
        if (item) {
            $("#clickdata").text("You clicked point " + item.dataIndex + " in " + item.series.label + ".");
            plot.highlight(item.series, item.datapoint);
        }
    });

	$("#loading").hide();
	$("#timewrap").hide();
	var plot = $.plot(placeholder, buildupData, options);
}

/*
 * Helper for showing tooltips on flot chart
 */
function showTooltip(x, y, contents) {
		if (x<800){
			x = x;
		} else if (x<1100){
			x = x-300;
		} else{
			x = x-560;
		}
        $('<div id="tooltip">' + contents + '</div>').css( {
            position: 'absolute',
            display: 'none',
            top: y + 5,
            left: x + 5,
            border: '1px solid #fdd',
            padding: '5px',
            'background-color': '#000',
			'color': '#FFF',
            opacity: 0.70,
			'font-size': '140%',
        }).appendTo("body").fadeIn(200);
}
</script>
{% endblock %}
